import { loginApi, logoutApi } from '@/http/api'

// 上次启动时的用户信息
let userInfoHistory = uni.getStorageSync('userInfo') || {};
let tokenHistory = uni.getStorageSync('token') || '';

let state = {
  //是否已经登录
  hasLogin: Boolean(Object.keys(userInfoHistory).length),
  //用户信息
  info: userInfoHistory,
  token: tokenHistory,
	//是否已经关注
	isConcern: true,
  isVip: 0
},
getters = {
  info(state) {
  	return state.info;
  },
  hasLogin(state) {
  	return state.hasLogin;
  },
  isConcern(state) {
    return state.isConcern;
  },
  isVip(state) {
    return state.isVip;
  }
},
mutations = {
  logout(state) {
    state.info = {};
    state.hasLogin = false;
    uni.setStorageSync('userInfo', {});
    uni.removeStorageSync('token');
    setTimeout(() => {
      window.location.reload();
    }, 1000);
  },
  SET_USERINFO: (state, res) => {

    //原有的结合传来的参数
    let _info = state.info;
    state.info = Object.assign({}, _info, res.user);
    //设置为已经登录
    if (!state.token) {
      state.token = res.token;
    }
    state.hasLogin = true;
    console.log('state.info', state.info);
    //存储最新的用户数据到本地持久化存储
    uni.setStorageSync('userInfo', state.info);
    uni.setStorageSync('token', state.token)
  },
  helpHit(state) {
    state.info.isFirst = 0;
  },
  hasConcern(state) {
    state.isConcern = true
  },
  cancelConcern(state) {
    state.isConcern = false
  }
},
actions = {
  // 登录
  Login({ commit }, param) {
    return new Promise((resolve, reject) => {
      loginApi(param).then(res => {
        if (res.code === 200) {
          commit('SET_USERINFO', res)
          resolve(res)
        } else {
          reject(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },
  Logout({ commit }) {
    // uni.showLoading({mask:true});
    logoutApi().then(res => {
      if (res.code === 200) {
        commit('logout');
        // uni.hideLoading();
      }
    })
  }
}
export default {
	namespaced: true,
	state,
	getters,
	mutations,
  actions
}